

cc.Class({
    extends: cc.AudioSource,

    properties: {
        isSoundEffect: true,

        audioFolder: {
            default: 'sound',
            visible: false
        }
    },

    onLoad() {
        this.maxAudioNumber = 20;
        // this._audios = [];

        cc.audioEngine.setMaxAudioInstance(this.maxAudioNumber);
    },
    onDestroy() {

    },

    play() {
        if (this.isSoundEffect && !game.player.enableSoundEffect) return;

        this._super();
    },

    openMusic() {
        this.play();
    },

    setClipAndPlay(file, additive = true) {
        if (this.isSoundEffect && !game.player.enableSoundEffect) return;

        cc.loader.loadRes(this.audioFolder +'/'+ file, cc.AudioClip, (err, clip) => {
            if (err) {
                cc.error(`Load audio error: ${err}`);
                return;
            }

            if (this.isPlaying && additive) {
                // let audio = this._audios.find(audio => !audio.isPlaying);
                // if (!audio) {
                //     if (this._audios.length < this.maxAudioNumber) {
                //         audio = this.node.addComponent(cc.AudioSource);
                //     } else {
                //         audio = this._audios.shift();
                //     }
                //     this._audios.push(audio);
                // }
                // audio.clip = clip;
                // audio.play();

                cc.audioEngine.playEffect(clip);
                return;
            }

            this.clip = clip;
            this.play();
        });
    },

    tapPlay(event, data) {
        this.setClipAndPlay(data);
    },

    toggleSoundEffect() {
        game.player.enableSoundEffect = !game.player.enableSoundEffect;
    }
});